package com.jack.helloworld.activity;

import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.jack.helloworld.R;

import androidx.appcompat.app.AppCompatActivity;

public class GestureDetectorActivity extends AppCompatActivity implements View.OnTouchListener {

    ImageView ivGestureDetector;
    GestureDetector gestureDetector;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture_detector);

        ivGestureDetector = (ImageView) findViewById(R.id.ivGestureDetector);
        ivGestureDetector.setOnTouchListener(this);
        gestureDetector = new GestureDetector(this, new MySimpleGestureDetector());
    }

    public class MySimpleGestureDetector extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

            if (e1.getX() - e2.getX() > 100) {
                Toast.makeText(GestureDetectorActivity.this, "从右往左滑动", Toast.LENGTH_SHORT).show();
            } else if (e2.getX() - e1. getX() > 100) {
                Toast.makeText(GestureDetectorActivity.this, "从左往右滑动", Toast.LENGTH_SHORT).show();
            }

            return super.onFling(e1, e2, velocityX, velocityY);
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        gestureDetector.onTouchEvent(event);
        return true;
    }
}
